<!--
 * @author  tanyuze
 新建/编辑标签
-->
<template>
  <div class="label-create">
    <div class="label-create-title">新建/编辑标签</div>
    <section v-loading="loading" class="label-create-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签类型" prop="labelType">
          <el-radio-group v-model="form.labelType">
            <el-radio
              v-for="(item, index) in dict.BQLX"
              :key="index"
              :label="item.dictValue"
              :value="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签形式" prop="showType">
          <el-radio-group v-model="form.showType">
            <el-radio
              v-for="(item, index) in dict.BQZSLX"
              :key="index"
              :label="item.dictValue"
              :value="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.showType === 'BQZSLX_TP'" label="标签图标" prop="labelImg" required>
          <el-button v-if="!fileInfo.imgId" type="primary" @click="handleUpload">上传图标</el-button>
          <div v-else>
            <el-image :src="view+ fileInfo.imgId" :preview-src-list="[view+fileInfo.imgId]">>
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </div>
        </el-form-item>
        <el-form-item v-if="form.showType === 'BQZSLX_TP'" label="图标宽度" prop="imgWidth">
          <el-input v-model.number="form.imgWidth" type="number" placeholder="请输入图标宽度" />
        </el-form-item>
        <el-form-item v-if="form.showType === 'BQZSLX_TP'" label="标签高度" prop="imgHeight">
          <el-input v-model.number="form.imgHeight" type="number" placeholder="请输入图标高度" />
        </el-form-item>
        <el-form-item v-if="form.showType === 'BQZSLX_WZ'" label="文字大小" prop="fontSize">
          <el-input v-model.number="form.fontSize" type="number" placeholder="请输入文字大小" />
        </el-form-item>
        <!--        <el-form-item v-if="form.showType === 'BQZSLX_WZ'" label="文字字体" prop="fontStyle">
          <el-select v-model="form.fontStyle" placeholder="请选择字体" clearable :style="{width:'100%'}">
            <el-option v-for="(item, index) in dict.WZZT" :key="index" :label="item.dictName" :value="item.dictValue" />
          </el-select>
        </el-form-item>-->
        <el-form-item v-if="form.showType === 'BQZSLX_WZ'" label="文字颜色" prop="fontColor">
          <div class="block">
            <el-color-picker v-model="form.fontColor" />
          </div>
        </el-form-item>
        <el-form-item v-if="form.showType === 'BQZSLX_WZ'" label="背景颜色" prop="labelColor">
          <div class="block">
            <el-color-picker v-model="form.labelColor" />
          </div>
        </el-form-item>
        <el-form-item label="命中值" prop="hitParam">
          <el-input v-model.trim="form.hitParam" placeholder="请输入命中值" />
        </el-form-item>
        <el-form-item label="说明" prop="explains">
          <el-input
            v-model="form.explains"
            :rows="6"
            type="textarea"
            placeholder="请输入说明"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="label-create-footer">
      <el-button style="padding: 10px 30px;" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit('form')">确 定</el-button>
    </section>
    <Upload
      v-if="uploadFile.showUpload"
      ref="upload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = false"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        只能上传：图片文件
      </div>
    </Upload>
  </div>
</template>

<script>
import Upload from '../components/upload'

import { insert, update, getDictByCode, get } from '../api/manage'

export default {
  name: 'StyleManage',
  components: { Upload },
  data() {
    return {
      loading: false,
      state: '',
      id: '',
      form: {
        classifyId: '',
        name: '', // 名称
        labelType: 'BQLX_JT', // 类型
        showType: 'BQZSLX_WZ', // 形式 文字 图片
        fontSize: '', // 大小
        // fontStyle: '', // 字体
        fontColor: '#b38888', // 颜色
        labelColor: '#b38888', // 背景
        hitParam: '', // 名中值
        explains: '', // 说明
        sort: '', // 排序
        labelImg: '', // 图标
        imgHeight: '',
        imgWidth: ''
      },
      uploadFile: {
        showUpload: false,
        accept: 'image/*',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: '',
        fileType: 'img'
      },
      rules: {
        name: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ],
        labelType: [
          { required: true, message: '请选择标签类型', trigger: 'change' }
        ],
        showType: [
          { required: true, message: '请选择标签形式', trigger: 'change' }
        ],
        fontSize: [
          { required: true, message: '请输入文字大小', trigger: 'blur' }
        ],
        /*  fontStyle: [
          { required: true, message: '请选择文字字体', trigger: 'change' }
        ],*/
        fontColor: [
          { required: true, message: '请选择文字颜色', trigger: 'change' }
        ],
        labelImg: [
          { required: true, message: '请上传标签图标', trigger: 'change' }
        ]
      },
      fileInfo: {},
      view: '/API-DOCUMENT/document/file/download?id=',
      dict: {
        BQZSLX: [], // 文字还是图片
        WZZT: [], // 字体
        BQLX: []// 动态静态
      }
    }
  },
  watch: {
    'form.showType'(newVal) {
      if (newVal) {
        this.$refs['form'].clearValidate()
      }
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.i) {
      this.id = this.$route.query.i
    }
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
      } else {
        this.getData()
      }
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 上传图标
     */
    handleUpload() {
      this.uploadFile.showUpload = true
    },
    /**
     * 上传成功
     */
    uploadSuccess(id, files, data) {
      if (id) {
        this.fileInfo.pictureName = files[0].name
        this.fileInfo.imgId = id
        this.form.labelImg = id
        this.uploadFile.showUpload = false
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: this.id }).then(res => {
          loading.close()
          const data = res.data.data
          const list = JSON.parse(res.data.data.labelConfig)
          delete data.labelConfig
          const query = { ...data, ...list }
          for (const key in this.form) {
            this.form[key] = query[key]
          }
          if (this.form.labelImg) {
            this.fileInfo.imgId = this.form.labelImg
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 提交
     */
    onSubmit() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            var query = {
              classifyId: this.id,
              name: this.form.name,
              labelType: this.form.labelType,
              showType: this.form.showType,
              hitParam: this.form.hitParam,
              explains: this.form.explains,
              sort: this.form.sort
            }
            var obj = {}
            if (this.form.showType === 'BQZSLX_WZ') {
              obj = {
                fontSize: this.form.fontSize,
                // fontStyle: this.form.fontStyle,
                fontColor: this.form.fontColor,
                labelColor: this.form.labelColor
              }
            } else {
              obj = {
                labelImg: this.form.labelImg,
                imgHeight: this.form.imgHeight,
                imgWidth: this.form.imgWidth
              }
            }
            query.labelConfig = JSON.stringify(obj)
            const params = Object.assign({}, query)
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.handleCancel()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            var query = {
              id: this.id,
              classifyId: this.form.classifyIds,
              name: this.form.name,
              labelType: this.form.labelType,
              showType: this.form.showType,
              hitParam: this.form.hitParam,
              explains: this.form.explains,
              sort: this.form.sort
            }
            var obj = {}
            if (this.form.showType === 'BQZSLX_WZ') {
              obj = {
                fontSize: this.form.fontSize,
                // fontStyle: this.form.fontStyle,
                fontColor: this.form.fontColor,
                labelColor: this.form.labelColor
              }
            } else {
              obj = {
                labelImg: this.form.labelImg,
                imgHeight: this.form.imgHeight,
                imgWidth: this.form.imgWidth
              }
            }
            query.labelConfig = JSON.stringify(obj)
            const params = Object.assign({}, query)
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.handleCancel()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 返回
     */
    handleCancel() {
      this.$router.replace({ path: this.$filterPath('index'), query: { }})
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.label-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .label-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .label-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }

      .el-image{
        width: 150px;
        height: 150px;
        img{
          width: 100%;
          height: 100%;
        }
      }
    }
    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }
    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }
    .news-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }
    .images-item {
      position: relative;
      margin-bottom: 10px;
      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }
      .el-input {
        display: block;
      }
      .custom-uploader {
        width: 100%;
        display: block;
        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }
      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;
        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }
        &.image-index-move {
          right: 40px;
        }
      }
    }
    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }
    .upload-img {
      width: 100%;
      height: 160px;
    }
    .attachment-item {
      margin-bottom: 10px;
      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }
      .video-item {
        position: relative;
        cursor: pointer;
        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;
          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }
          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .label-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;
      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }
    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
